4. js对象克隆

  • 数据类型在内存中的存储:
  • 基本数据类型(Number、String、Boolean、Null、undefined、Symbol)存储在栈内存中
  • 引用数据类型对象的地址存储在栈内存中,对象存储在堆中
  • 浅拷贝
  1. // 1. Object.assign
  2. function copy(obj) {
  3. return Object.assign({}, obj);
  4. }
  5. // 2. ...展开运算符
  6. function copy(obj){
  7. return {...obj};
  8. }
  • 深拷贝
  1. function copy(obj) {
  2. if (obj === null) return null;
  3. if(obj.constructor !== Object) return obj;
  4. if(obj.constructor === Date) return new Date(obj);
  5. if(obj.constructor === RegExp) return new RegExp(obj);
  6. var newObj = new obj.constructor(); //保持继承的原型
  7. for(var key in obj){
  8. if(obj.hasOwnProperty(key)){
  9. var val = obj[key];
  10. newObj[key] = typeof val === 'object' ? arguments.callee(val):val;
  11. }
  12. }
  13. return newObj;
  14. }